package com.hwadee.backend.service;

import com.hwadee.backend.entity.Apply;
import com.hwadee.backend.entity.Authorize;
import com.hwadee.backend.mapper.ApplyMapper;
import com.hwadee.backend.mapper.AuthorizeMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ApplyService extends ServiceImpl<ApplyMapper, Apply> {
    private final ApplyMapper applyMapper;
    private final AuthorizeMapper authorizeMapper;

    @Autowired
    public ApplyService(ApplyMapper applyMapper, AuthorizeMapper authorizeMapper) {
        this.applyMapper = applyMapper;
        this.authorizeMapper = authorizeMapper;
    }

    // 医生提交授权申请
    public int createApply(int applicantId, int targetUserId) {
        // 检查是否已存在待处理申请
        Apply existingApply = applyMapper.selectByApplicantAndTarget(applicantId, targetUserId);
        if (existingApply != null && "pending".equals(existingApply.getStatus())) {
            return -1; // 已存在待处理申请
        }
        Apply apply = new Apply();
        apply.setApplicantId(applicantId);
        apply.setTargetUserId(targetUserId);
        apply.setStatus("pending");
        apply.setCreateTime(LocalDateTime.now());
        apply.setUpdateTime(LocalDateTime.now());

        return applyMapper.insert(apply);
    }

    // 用户处理申请（同意/拒绝）
    @Transactional
    public int handleApply(int applyId, String status) {
        Apply apply = applyMapper.selectById(applyId);
        System.out.println("查询到的申请记录: " + apply);
        if (apply == null) {
            System.out.println("申请不存在，apply: " + apply);
            return -1; // 申请不存在
        }

        // 如果申请被同意，创建授权记录
        if ("approved".equals(status)) {
            Authorize authorize = new Authorize();
            authorize.setApplicant(apply.getApplicantId());
            authorize.setResponse(apply.getTargetUserId());
            authorize.setStatus("approved");
            authorize.setCreateTime(LocalDateTime.now());
            authorize.setUpdateTime(LocalDateTime.now());
            authorizeMapper.insert(authorize);
        }

        // 从apply表中删除记录
        int deleteResult = applyMapper.deleteById(applyId);
        System.out.println("删除结果: " + deleteResult);

        return deleteResult;
    }

    // 根据申请人和目标用户查询申请记录
    public Apply getApplyByApplicantAndTarget(int applicantId, int targetUserId) {
        return applyMapper.selectByApplicantAndTarget(applicantId, targetUserId);
    }

    // 根据申请人ID查询申请列表
    public List<Apply> getAppliesByApplicant(int applicantId) {
        return applyMapper.selectByApplicantId(applicantId);
    }

    // 根据目标用户ID查询申请列表
    public List<Apply> getAppliesByTargetUser(int targetUserId) {
        return applyMapper.selectByTargetUserId(targetUserId);
    }
}